<template>
  <div class="app-container">
    <transition :enter-active-class="animate.searchAnimate.enter" :leave-active-class="animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="商户名称" prop="account" v-if="isAdmin">
              <el-input v-model="queryParams.createName" placeholder="请输入商户名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="邮件主题" prop="theme">
              <el-input v-model="queryParams.theme" placeholder="请输入邮件主题" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in email_queue_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    
    <el-tooltip :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
      <div ref="searchIcon" class="search_icon" :class="showSearch ? 'show' : 'hide'" @click="showSearch = !showSearch">
        <svg-icon icon-class="commencement"></svg-icon>
      </div>
    </el-tooltip>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:EmailQueue:add']" type="primary" plain icon="Plus" size="mini" @click="handleAdd">新增 </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:EmailQueue:edit']" type="success" plain icon="Edit" size="mini" :disabled="single" @click="handleUpdate"
                >修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['system:EmailQueue:remove']"
                type="danger"
                plain
                icon="Delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                >删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:EmailQueue:export']" type="warning" plain icon="Download" size="mini" @click="handleExport"
                >导出
              </el-button>
            </el-col>
            <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
          </el-row>

          <div class="flex items-center w-fit gap-5">
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :page-sizes="[20, 50, 100, 300]"
              :total="total"
              style="height: 30px; margin: 0; padding: 0 !important"
              @pagination="getList"
            />
            <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="EmailQueueList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商户名称" v-if="isAdmin" align="center" prop="createName" />
        <!--      <el-table-column label="队列标题" align="center" prop="title"/>-->
        <el-table-column label="邮件主题" align="center" prop="theme">
          <template #default="scope">
            <a style="color: #1890ff" @click="handleView(scope.row)">{{ scope.row.theme }}</a>
          </template>
        </el-table-column>
        <el-table-column label="发件邮箱" align="center" prop="sendEmailAct" width="220" />
        <el-table-column label="队列状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="email_queue_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="报错时间" align="center" prop="errTime" width="180" />
        <el-table-column label="报错内容" align="center" prop="errContent" show-overflow-tooltip />
        <el-table-column label="完成时间" align="center" prop="completeTime" width="180" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 1"
              v-hasPermi="['system:EmailQueue:send']"
              size="mini"
              type="text"
              icon="Promotion"
              @click="sendEmail(scope.row, 1)"
            >
              发送
            </el-button>
            <!-- <el-button
            v-if="scope.row.status === 3 || scope.row.status === 4"
            v-hasPermi="['system:EmailQueue:send']"
            size="mini"
            type="text"
            icon="Promotion"
            @click="sendEmail(scope.row, 4)"
          >
            失败重发
          </el-button> -->
            <el-button
              v-if="scope.row.status === 4"
              v-hasPermi="['system:EmailQueue:send']"
              size="mini"
              type="text"
              icon="Promotion"
              @click="sendEmail(scope.row, 4)"
            >
              失败重发
            </el-button>
            <el-button
              v-if="!(scope.row.status == 2 || scope.row.status == 3)"
              v-hasPermi="['system:EmailQueue:edit']"
              size="mini"
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            >
              修改
            </el-button>
            <el-button v-hasPermi="['system:EmailQueue:remove']" size="mini" type="text" icon="Delete" @click="handleDelete(scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-5 mr-[-0.5rem]">
        <div class="flex justify-end items-center w-fit gap-5">
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :page-sizes="[20, 50, 100, 300]"
            :total="total"
            style="height: 30px; margin: 0; padding: 0 !important"
            @pagination="getList"
          />
          <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
        </div>
      </div>
    </el-card>

    <!-- 添加或修改邮件队列对话框 -->
    <el-dialog v-model="open" :title="title" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="发件邮箱" prop="sendEmailIdList">
              <el-select v-if="form.queueId" v-model="form.sendEmailIdList" placeholder="请选择发件邮箱" multiple style="width: 100%">
                <el-option v-for="item in EmailAccountList" :key="item.id" :label="item.account" :value="item.id" />
              </el-select>

              <el-select v-else v-model="form.sendEmailIdList" placeholder="请选择发件邮箱" multiple style="width: 100%">
                <el-option v-for="item in EmailAccountListIng" :key="item.id" :label="item.account" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮件类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择邮件类型" style="width: 100%">
                <template v-for="dict in email_queue_type">
                  <el-option v-if="dict.value === '1'" :key="dict.value" :label="dict.label" :value="dict.value" />
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮件模板" prop="templateId">
              <el-select v-model="form.templateId" placeholder="请选择邮件模板" style="width: 100%">
                <el-option v-for="item in templateList" :key="item.templateId" :label="item.name" :value="item.templateId" />
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="延迟时间（分钟）" prop="delayTime" label-width="140px">-->
          <!--              <el-input-number v-model="form.delayTime" :min="1" label="请输入延迟时间"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="每次发送条数" prop="delaySendNum" label-width="120px">-->
          <!--              <el-input-number v-model="form.delaySendNum" :min="1" label="请输入发送条数"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12" v-if="form.queueId == null">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <template v-for="dict in email_queue_status">
                  <el-option
                    v-if="dict.value == 1 || dict.value == 2"
                    :key="dict.value"
                    :label="dict.label == '发送中' ? '直接发送' : dict.label"
                    :value="parseInt(dict.value)"
                  ></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="延迟发送" prop="isDelay">
              <el-switch v-model="form.isDelay" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.isDelay == 1">
            <el-form-item label="分钟" prop="delayTime">
              <el-input-number style="width: 100%" v-model="form.delayTime" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.isDelay == 1">
            <el-form-item label="发送条数" prop="delaySendNum">
              <el-input-number style="width: 100%" v-model="form.delaySendNum" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <!--        <el-form-item label="邮件主题" prop="theme">-->
        <!--          <el-input v-model="form.theme" placeholder="请输入邮件主题"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="邮件模板">-->
        <!--          <vue-ueditor-wrap :config="ueditorConfig" v-model="form.template"></vue-ueditor-wrap>-->
        <!--        </el-form-item>-->

        <el-row v-if="form.queueId == null" :gutter="10" class="mb8">
          <el-col :span="5">
            <el-upload ref="upload" class="upload-demo" accept=".xls,.xlsx" action="javascript:void(0)" :on-change="uploadExcel" :auto-upload="false">
              <el-button size="small" icon="Plus" type="primary">上传表格</el-button>
            </el-upload>
          </el-col>
          <el-col :span="1.5">
            <a style="color: #00afff" href="/%E7%89%A9%E6%B5%81%E9%82%AE%E4%BB%B6%E6%A8%A1%E6%9D%BF%E7%A4%BA%E4%BE%8B.xlsx" target="_blank"
              >下载模板</a
            >
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看邮件队列对话框 -->
    <el-dialog v-model="viewDialog" :title="title" width="50%" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="发件邮箱" prop="sendEmailIdList">
              <el-select :model-value="form.sendEmailIdList" placeholder="请选择发件邮箱" multiple style="width: 100%">
                <el-option v-for="item in EmailAccountList" :key="item.id" :label="item.account" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮件类型" prop="type">
              <el-select :model-value="form.type" placeholder="请选择邮件类型" style="width: 100%">
                <template v-for="dict in email_queue_type">
                  <el-option v-if="dict.value === '1'" :key="dict.value" :label="dict.label" :value="dict.value" />
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮件模板" prop="templateId">
              <el-select :model-value="form.templateId" placeholder="请选择邮件模板" style="width: 100%">
                <el-option v-for="item in templateList" :key="item.templateId" :label="item.name" :value="item.templateId" />
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="延迟时间（分钟）" prop="delayTime" label-width="140px">-->
          <!--              <el-input-number :value="form.delayTime" :min="1" label="请输入延迟时间"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="每次发送条数" prop="delaySendNum" label-width="120px">-->
          <!--              <el-input-number :value="form.delaySendNum" :min="1" label="请输入发送条数"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select :model-value="form.status" placeholder="请选择状态">
                <el-option v-for="dict in email_queue_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="延迟发送" prop="isDelay">
              <el-switch :model-value="form.isDelay" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.isDelay == 1">
            <el-form-item label="分钟" prop="delayTime">
              <el-input-number style="width: 100%" :model-value="form.delayTime" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.isDelay == 1">
            <el-form-item label="发送条数" prop="delaySendNum">
              <el-input-number style="width: 100%" :model-value="form.delaySendNum" />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewCancel">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listEmailQueue,
  getEmailQueue,
  getEmailMainInfo,
  delEmailQueue,
  addEmailQueue,
  updateEmailQueue,
  sendEmailQueue
} from '@/api/email/EmailQueue';
import useUserStore from '@/store/modules/user';
import { selectlistEmailTemplate } from '@/api/email/EmailTemplate';
import { listEmailAccount } from '@/api/email/EmailAccount';
import xlsx from 'xlsx';
import { parseTime } from '@/utils/ruoyi';
export default {
  name: 'EmailQueue',
  data() {
    return {
      email_queue_status: [],
      email_status: [],
      email_queue_type: [],
      ueditorConfig: {
        toolbars: [
          [
            'source', //源代码
            'undo', //撤销
            'redo', //重做
            'bold', //加粗
            'indent', //首行缩进
            'snapscreen', //截图
            'italic', //斜体
            'underline', //下划线
            'print', //打印
            'horizontal', //分隔线
            'inserttable', //插入表格
            'edittable', //表格属性
            'insertrow', //前插入行
            'insertcol', //前插入列
            'mergeright', //右合并单元格
            'mergedown', //下合并单元格
            'deleterow', //删除行
            'deletecol', //删除列
            'splittorows', //拆分成行
            'splittocols', //拆分成列
            'splittocells', //完全拆分单元格
            'deletecaption', //删除表格标题
            'inserttitle', //插入标题
            'mergecells', //合并多个单元格
            'edittd', //单元格属性
            'deletetable', //删除表格
            // 'fontfamily', //字体
            // 'fontsize', //字号
            // 'paragraph', //段落格式
            'simpleupload', //单图上传
            'insertimage', //多图上传
            'attachment', //附件
            'link', //超链接
            'emotion', //表情
            'spechars', //特殊字符
            'searchreplace', //查询替换
            'map', //Baidu地图
            'justifyleft', //居左对齐
            'justifyright', //居右对齐
            'justifycenter', //居中对齐
            'justifyjustify', //两端对齐
            'forecolor', //字体颜色
            'backcolor', //背景色
            'insertorderedlist', //有序列表
            'insertunorderedlist', //无序列表
            'rowspacingtop', //段前距
            'rowspacingbottom', //段后距
            'lineheight', //行间距
            'autotypeset', //自动排版
            'template', //模板
            'scrawl' //涂鸦
          ]
        ],
        autoHeightEnabled: true,
        initialFrameHeight: 300
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedEmailList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 邮件队列表格数据
      EmailQueueList: [],
      // 可用邮箱账号
      EmailAccountList: [],
      // 邮件列表表格数据
      emailList: [],
      // 邮件模板列表
      templateList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示查看弹窗
      viewDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        type: '1',
        title: null,
        theme: null,
        sendEmailId: null,
        sendEmailIdList: [],
        status: null
      },
      // 表单参数
      form: {},
      fileList: [],
      // 表单校验
      rules: {
        sendEmailIdList: [{ required: true, message: '发件邮箱不能为空', trigger: 'change' }],
        type: [{ required: true, message: '邮件类型不能为空', trigger: 'change' }],
        templateId: [{ required: true, message: '邮件模板不能为空', trigger: 'change' }],
        delayTime: [{ required: true, message: '延迟时间不能为空', trigger: 'change' }],
        delaySendNum: [{ required: true, message: '发送条数不能为空', trigger: 'change' }],
        title: [{ required: true, message: '队列标题不能为空', trigger: 'blur' }],
        theme: [{ required: true, message: '邮件主题不能为空', trigger: 'blur' }],
        template: [{ required: true, message: '邮件模板不能为空', trigger: 'blur' }],
        isDelay: [{ required: true, message: '状态不能为空', trigger: 'change' }],
        delayTime: [{ required: true, message: '发送分钟数不能为空', trigger: 'change' }],
        delaySendNum: [{ required: true, message: '发送条数不能为空', trigger: 'change' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
      }
    };
  },
  async created() {
    let res = await this.useDict('email_queue_status', 'email_queue_type', 'email_status');
    await this.getList();
    setTimeout(() => {
      this.email_queue_status = res.email_queue_status;
      this.email_queue_type = res.email_queue_type;
      this.email_status = res.email_status;
    }, 1000);
  },
  computed: {
    isAdmin() {
      const { isAdmin } = useUserStore();
      return isAdmin;
    },
    EmailAccountListIng() {
      return this.EmailAccountList.filter((item) => item.status == 0);
    }
  },
  methods: {
    sendEmail(row, status) {
      ElMessageBox.confirm('确认是否发送邮件信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.status === 2) {
          this.$modal.msgError('该队列当前状态不能发送');
          return;
        }
        sendEmailQueue(row.queueId, status).then((response) => {
          this.$modal.msgSuccess('操作成功！');
          this.getList();
        });
      });
    },
    getTemplate() {
      selectlistEmailTemplate({ isPage: false, status: 1, type: 2 }).then((response) => {
        this.templateList = response.data;
      });
    },
    /** 查询邮件队列列表 */
    getList() {
      this.loading = true;
      listEmailQueue(this.queryParams).then((response) => {
        this.EmailQueueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 查看关闭
    viewCancel() {
      this.viewDialog = false;
      this.reset();
    },

    /** 查看队列信息 */
    handleView(row) {
      this.reset();
      this.getTemplate();
      this.loadAccount();
      const queueId = row.queueId;

      getEmailMainInfo(queueId).then((response) => {
        let data = response.data;
        this.form.queueId = data.queueId;
        this.form.sendEmailIdList = data.sendEmailId.split(',').map(Number);
        this.form.type = data.type + '';
        this.form.templateId = data.templateId;
        this.form.delayTime = data.delayTime;
        this.form.status = data.status;

        this.form.isDelay = data.isDelay;
        this.form.delaySendNum = data.delaySendNum;
        this.viewDialog = true;
        this.title = '邮件队列详情';
      });
      this.loadAccount();
    },
    // 表单重置
    reset() {
      this.form = {
        queueId: null,
        type: '1',
        templateId: null,
        title: null,
        theme: null,
        template: '',
        sendEmailId: null,
        sendEmailIdList: [],
        sendEmailAct: null,
        delayTime: 60,
        delaySendNum: 100,
        status: 1,
        completeTime: null,
        isDelete: null,
        deptId: null,
        createId: null,
        createName: null,
        createTime: null,
        updateId: null,
        updateName: null,
        updateTime: null
      };
      this.emailList = [];
      this.$refs.form?.resetFields();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      Object.assign(this.queryParams, {
        pageNum: 1,
        pageSize: 10,
        type: '1',
        title: null,
        theme: null,
        sendEmailId: null,
        sendEmailIdList: [],
        status: null,
        createName: ''
      });
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.queueId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTemplate();
      this.open = true;
      this.title = '添加邮件队列';
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
      this.loadAccount();
    },
    /*加载邮箱账号*/
    loadAccount() {
      listEmailAccount({ page: false }).then((response) => {
        this.EmailAccountList = response.rows;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTemplate();
      this.loadAccount();
      const queueId = row.queueId || this.ids;

      getEmailMainInfo(queueId).then((response) => {
        let data = response.data;
        this.form.queueId = data.queueId;
        this.form.sendEmailIdList = data.sendEmailId.split(',').map(Number);
        this.form.type = data.type + '';
        this.form.templateId = data.templateId;
        this.form.isDelay = data.isDelay;
        this.form.delayTime = data.delayTime;
        this.form.delaySendNum = data.delaySendNum;
        this.form.status = data.status;
        this.open = true;
        this.title = '修改邮件队列';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid && this.validateContent()) {
          this.form.emailList = this.emailList;
          this.form.sendEmailId = this.form.sendEmailIdList.join(',');
          this.form.sendEmailAct = this.EmailAccountList.filter((i) => this.form.sendEmailIdList.includes(i.id))
            .map((tmp) => tmp.account)
            .join(',');

          if (this.form.queueId != null) {
            updateEmailQueue(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            this.form.title = parseTime(new Date()) + ' 邮件队列';

            addEmailQueue(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    uploadExcel(file, fileList) {
      const files = { 0: file.raw }; // 取到File
      this.readExcel(files);
    },
    readExcel(files) {
      // 表格导入
      if (files.length <= 0) {
        // 如果没有文件名
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$modal.msgError('上传格式不正确，请上传xls或者xlsx格式');
        return false;
      }

      const fileReader = new FileReader();
      fileReader.onload = (files) => {
        try {
          const data = files.target.result;
          const workbook = xlsx.read(data, {
            type: 'binary'
          });

          const wsname = workbook.SheetNames[0]; // 取第一张表
          const ws = xlsx.utils.sheet_to_json(workbook.Sheets[wsname]); // 生成json表格内容

          if (ws == null || ws.length === 0) {
            this.$modal.msgError('未读取到表格数据，请重新上传表格');
            this.$refs.upload.clearFiles();
          } else {
            this.emailList = ws.map((obj) => {
              let item = {};
              item.orderNo = obj['B端订单号'];
              if (item.orderNo === undefined || item.orderNo == null || item.orderNo === '') {
                this.$modal.msgError('未读取到表格中有【B端订单号】列');
                this.$refs.upload.clearFiles();
                throw new Error('未读取到表格中有【B端订单号】列');
              }
              // Object.keys(obj).forEach((key)=>{
              //     if(key !== 'B端订单号' && (!key.includes("{") || !key.includes("}"))){
              //         this.$modal.msgError('表格的数据列必须用{}包含哦');
              //         this.$refs.upload.clearFiles();
              //         throw new Error('表格的数据列必须用{}包含哦');
              //     }
              // });
              item.dyncParam = JSON.stringify(obj);
              return item;
            });
          }
          // 重写数据
          // this.$refs.upload.value = ''
          // return ws
        } catch (e) {
          console.log(e);
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    /** 验证邮件内容 */
    validateContent() {
      if (this.form.queueId == null && this.emailList.length === 0) {
        this.$modal.msgError('请上传表格数据');
        return false;
      }
      return true;
    },
    /** 取出中括号内的内容 */
    getBracketStr(text) {
      let result = '';
      if (text == null || text.length === 0) {
        return result;
      }
      let regex = /\[(.+?)\]/g;
      let options = text.match(regex);
      if (options !== undefined && options != null) {
        let option = options[0];
        if (option !== undefined && option != null) {
          result = option.substring(1, option.length - 1);
        }
      }
      return result;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const queueIds = row.queueId || this.ids;
      this.$modal
        .confirm('是否确认删除此条邮件队列的数据项？')
        .then(function () {
          return delEmailQueue(queueIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 全部删除按钮操作 */
    handleDeleteAll(row) {
      const queueIds = row.queueId || this.ids;
      this.$modal
        .confirm('是否确认删除所有邮件队列的数据项？')
        .then(function () {
          return delEmailQueue(queueIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/EmailQueue/export',
        {
          ...this.queryParams
        },
        `EmailQueue_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>

<!--<script>-->
<!--import { defineComponent } from 'vue';-->
<!--export default defineComponent({-->
<!--  setup() {-->
<!--    return {-->
<!--      -->
<!--    };-->
<!--  }-->
<!--});-->
<!--</script>-->
